/*
 * @(#)WorkflowStage.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.workflow.bean.WorkflowStage;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.web.ListWorkflowStageForm;
/**
 * WorkflowStageDAObject.java
 *
 * This class is the data access bean for table "WORKFLOW_STAGE".
 *
 * @author dick xie
 * @company DCIVision Limited
 * @creation date 08/06/2005
 * @version $Revision: 1.13.20.1 $
 */

public class WorkflowStageDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.13.20.1 $";

  public static final String TABLE_NAME = "WORKFLOW_STAGE";

  public WorkflowStageDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("WORKFLOW_RECORD_ID");
    this.vecDBColumn.add("STAGE_NAME");
    this.vecDBColumn.add("DURATION");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          return(tmpWorkflowStage);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          tmpWorkflowStage.setRecordCount(totalNumOfRecord);
          tmpWorkflowStage.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpWorkflowStage);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  public synchronized List getWorkflowStageList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    ListWorkflowStageForm listStageForm = (ListWorkflowStageForm)searchForm;
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ,WORKFLOW_RECORD B ");
        sqlStat.append("WHERE  A.WORKFLOW_RECORD_ID =B.ID AND A.RECORD_STATUS = ? ");
        if (!Utility.isEmpty(listStageForm.getWorkflowRecordID())) {
          sqlStat.append(" AND  A.WORKFLOW_RECORD_ID = ? ");
        }
        if (!Utility.isEmpty(listStageForm.getWorkflowGroupID())) {
          sqlStat.append(" AND  B.WORKFLOW_GROUP_ID = ? ");
        }
        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField;
          if((searchForm.getBasicSearchField()).equals("WORKFLOW_CODE")){
            searchField ="B.WORKFLOW_CODE";
          }else{
            //searchField = searchForm.getBasicSearchField();
            searchField="STAGE_NAME";
          }
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }
        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = null;
          if ("STEP_NAME".equals(searchForm.getSortAttribute())) {
            sortAttribute = "STAGE_NAME";
          } else {
            sortAttribute = searchForm.getSortAttribute();
          }
          if(sortAttribute.indexOf(".") < 0 && sortAttribute.equals("WORKFLOW_RECORD_ID")){
            sortAttribute="B.WORKFLOW_CODE";
          }else if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int i=1;
        this.setPrepareStatement(preStatCnt, i++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (!Utility.isEmpty(listStageForm.getWorkflowRecordID())) {
          this.setPrepareStatement(preStatCnt, i++, new Integer(listStageForm.getWorkflowRecordID()));
        }
        if (!Utility.isEmpty(listStageForm.getWorkflowGroupID())) {
          this.setPrepareStatement(preStatCnt, i++, new Integer(listStageForm.getWorkflowGroupID()));
        }
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, i++, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        int j=1;
        this.setPrepareStatement(preStat, j++, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (!Utility.isEmpty(listStageForm.getWorkflowRecordID())) {
          this.setPrepareStatement(preStat, j++, new Integer(listStageForm.getWorkflowRecordID()));
        }
        if (!Utility.isEmpty(listStageForm.getWorkflowGroupID())) {
          this.setPrepareStatement(preStat, j++, new Integer(listStageForm.getWorkflowGroupID()));
        }
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, j++, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          tmpWorkflowStage.setRecordCount(totalNumOfRecord);
          tmpWorkflowStage.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpWorkflowStage);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }


  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          result.add(tmpWorkflowStage);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    WorkflowStage tmpWorkflowStage = (WorkflowStage)((WorkflowStage)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   WORKFLOW_STAGE(ID, WORKFLOW_RECORD_ID, STAGE_NAME, DURATION, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpWorkflowStage.getWorkflowRecordID());
        setPrepareStatement(preStat, 3, tmpWorkflowStage.getStageName());
        setPrepareStatement(preStat, 4, tmpWorkflowStage.getDuration());
        setPrepareStatement(preStat, 5, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 6, new Integer(0));
        setPrepareStatement(preStat, 7, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 8, currTime);
        setPrepareStatement(preStat, 9, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 10, currTime);
        preStat.executeUpdate();
        tmpWorkflowStage.setID(nextID);
        tmpWorkflowStage.setCreatorID(sessionContainer.getUserRecordID());
        tmpWorkflowStage.setCreateDate(currTime);
        tmpWorkflowStage.setUpdaterID(sessionContainer.getUserRecordID());
        tmpWorkflowStage.setUpdateDate(currTime);
        tmpWorkflowStage.setUpdateCount(new Integer(0));
        tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
        tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
        return(tmpWorkflowStage);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    WorkflowStage tmpWorkflowStage = (WorkflowStage)((WorkflowStage)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE WORKFLOW_STAGE ");
        sqlStat.append("SET  WORKFLOW_RECORD_ID=?, STAGE_NAME=?, DURATION=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpWorkflowStage.getWorkflowRecordID());
        setPrepareStatement(preStat, 2, tmpWorkflowStage.getStageName());
        setPrepareStatement(preStat, 3, tmpWorkflowStage.getDuration());
        setPrepareStatement(preStat, 4, new Integer(tmpWorkflowStage.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 5, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 6, currTime);
        setPrepareStatement(preStat, 7, tmpWorkflowStage.getID());
        setPrepareStatement(preStat, 8, tmpWorkflowStage.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpWorkflowStage.setUpdaterID(sessionContainer.getUserRecordID());
          tmpWorkflowStage.setUpdateDate(currTime);
          tmpWorkflowStage.setUpdateCount(new Integer(tmpWorkflowStage.getUpdateCount().intValue() + 1));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          return(tmpWorkflowStage);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    WorkflowStage tmpWorkflowStage = (WorkflowStage)((WorkflowStage)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   WORKFLOW_STAGE ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpWorkflowStage.getID());
        setPrepareStatement(preStat, 2, tmpWorkflowStage.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpWorkflowStage);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    WorkflowStage tmpWorkflowStage = (WorkflowStage)this.oldValue;

    if (tmpWorkflowStage != null) {
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getID()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getWorkflowRecordID()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getStageName()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getDuration()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdateDate()));
    }

    tmpWorkflowStage = (WorkflowStage)obj;
    if (tmpWorkflowStage != null) {
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getID()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getWorkflowRecordID()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getStageName()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getDuration()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpWorkflowStage.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/
  /**
   * Gets all the workflow Stages of the given workflow record
   *
   * @param workflowRecordID The workflow record ID
   * @return List of WorkflowStage objects
   * @throws ApplicationException
   * @see com.dcivision.workflow.bean.WorkflowStep
   * @see com.dcivision.workflow.bean.WorkflowRecord
   */
  public synchronized List getListByWorkflowRecordID(Integer workflowRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append(" AND  A.WORKFLOW_RECORD_ID = ? ");
        sqlStat.append(" ORDER BY A.ID ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, workflowRecordID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          result.add(tmpWorkflowStage);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  /**
   * Gets all the workflow step(s) which not belong to any workflow stage of the given workflow record
   *
   * @param workflowRecordID The workflow record ID
   * @return List of WorkflowStep objects
   * @throws ApplicationException
   * @see com.dcivision.workflow.bean.WorkflowStep
   * @see com.dcivision.workflow.bean.WorkflowRecord
   */
  public synchronized List getWorkflowStepListByWorkflowRecordID(Integer workflowRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT DISTINCT(A.ID), A.STEP_NAME, A.STEP_SEQ , B.WORKFLOW_STAGE_ID ");
        sqlStat.append(" FROM WORKFLOW_STEP A LEFT JOIN  MTM_WF_STAGE_WF_STEP B ON (B.RECORD_STATUS=? AND A.ID=B.WORKFLOW_STEP_ID) ");
        sqlStat.append(" WHERE B.WORKFLOW_STAGE_ID IS NULL  AND A.RECORD_STATUS= ? AND A.WORKFLOW_RECORD_ID=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, workflowRecordID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStep tmpWorkflowStep = new WorkflowStep();
          tmpWorkflowStep.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStep.setStepName(getResultSetString(rs, "STEP_NAME"));
          tmpWorkflowStep.setStepSeq(getResultSetInteger(rs, "STEP_SEQ"));
          result.add(tmpWorkflowStep);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  /**
   * Gets all the workflow step(s) which not belong to any workflow stage of the given workflow record and workflow stage
   *
   * @param workflowRecordID The workflow record ID
   * @param workflowStageID The workflow stage ID
   * @return List of WorkflowStep objects
   * @throws ApplicationException
   * @see com.dcivision.workflow.bean.WorkflowStep
   * @see com.dcivision.workflow.bean.WorkflowRecord
   */
  public synchronized List getWorkflowStepListByWorkflowRecordIDAndStageID(Integer workflowRecordID, Integer workflowStageID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT DISTINCT A.ID, A.STEP_NAME, A.STEP_SEQ ");
        sqlStat.append(" FROM WORKFLOW_STEP A LEFT JOIN MTM_WF_STAGE_WF_STEP B ON A.ID=B.WORKFLOW_STEP_ID ");
        sqlStat.append(" WHERE ((B.WORKFLOW_STAGE_ID = ? AND B.RECORD_STATUS <> ? ) OR B.WORKFLOW_STAGE_ID IS NULL )  AND A.RECORD_STATUS= ? AND A.WORKFLOW_RECORD_ID=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, workflowStageID);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_INACTIVE);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 4, workflowRecordID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStep tmpWorkflowStep = new WorkflowStep();
          tmpWorkflowStep.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStep.setStepName(getResultSetString(rs, "STEP_NAME"));
          tmpWorkflowStep.setStepSeq(getResultSetInteger(rs, "STEP_SEQ"));
          result.add(tmpWorkflowStep);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  /**
   * Gets a list of WorkflowStep object for given searchForm of AbstractSearchForm object
   * @param searchForm The AbstractSearchForm object
   * @return list of WorkflowStep object
   * @throws ApplicationException
   * @see com.dcivision.workflow.bean.WorkflowStep
   */
  public synchronized List getFullWorkflowStepList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    ListWorkflowStageForm listStageForm = (ListWorkflowStageForm)searchForm;
    Integer workflowRecordID = new Integer(1);
    if (!Utility.isEmpty(listStageForm.getWorkflowRecordID())){
      workflowRecordID = new Integer(listStageForm.getWorkflowRecordID());
    }
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.STEP_NAME, A.STEP_SEQ, A.DESCRIPTION, B.WORKFLOW_STAGE_ID, B.RECORD_STATUS, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM WORKFLOW_STEP A LEFT JOIN MTM_WF_STAGE_WF_STEP B ON A.ID=B.WORKFLOW_STEP_ID ");
        sqlStat.append(" WHERE  A.RECORD_STATUS = ?   AND A.WORKFLOW_RECORD_ID = ? AND (B.RECORD_STATUS <> ? OR B.RECORD_STATUS IS NULL) ");

        //      Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = null;
          if ("STAGE_NAME".equals(searchForm.getSortAttribute())) {
            sortAttribute = "STEP_SEQ";
          } else {
            sortAttribute = searchForm.getSortAttribute();
          }
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, workflowRecordID);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_INACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 4, searchKeyword);
        }
        log.debug(sqlStat.toString());
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStep tmpWorkflowStep = new WorkflowStep();
          tmpWorkflowStep.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStep.setStepName(getResultSetString(rs, "STEP_NAME"));
          tmpWorkflowStep.setStepSeq(getResultSetInteger(rs, "STEP_SEQ"));
          tmpWorkflowStep.setDescription(getResultSetString(rs, "DESCRIPTION"));
          if (!Utility.isEmpty(getResultSetInteger(rs, "WORKFLOW_STAGE_ID"))) {
            tmpWorkflowStep.setWorkflowStageID(getResultSetInteger(rs, "WORKFLOW_STAGE_ID"));
          } else {
            tmpWorkflowStep.setWorkflowStageID(new Integer(-1));
          }
          tmpWorkflowStep.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStep.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStep.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStep.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStep.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStep.getUpdaterID()));
          result.add(tmpWorkflowStep);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized List getListByStageNameAndWorkflowRecordID(String stageName, Integer workflowRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.STAGE_NAME = ? AND A.WORKFLOW_RECORD_ID = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, stageName);
        this.setPrepareStatement(preStat, 3, workflowRecordID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          result.add(tmpWorkflowStage);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * get object by workflow step ID
   * @param workflowStepID
   * @return AbstractBaseObject
   * @throws ApplicationException
   */
  public synchronized AbstractBaseObject getObjectByWorkflowStepID(Integer workflowStepID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.WORKFLOW_RECORD_ID, A.STAGE_NAME, A.DURATION, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   WORKFLOW_STAGE A , MTM_WF_STAGE_WF_STEP B ");
        sqlStat.append("WHERE  A.ID = B.WORKFLOW_STAGE_ID AND B.WORKFLOW_STEP_ID = ? AND A.RECORD_STATUS = ? AND A.RECORD_STATUS = B.RECORD_STATUS ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, workflowStepID);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          WorkflowStage tmpWorkflowStage = new WorkflowStage();
          tmpWorkflowStage.setID(getResultSetInteger(rs, "ID"));
          tmpWorkflowStage.setWorkflowRecordID(getResultSetInteger(rs, "WORKFLOW_RECORD_ID"));
          tmpWorkflowStage.setStageName(getResultSetString(rs, "STAGE_NAME"));
          tmpWorkflowStage.setDuration(getResultSetInteger(rs, "DURATION"));
          tmpWorkflowStage.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpWorkflowStage.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpWorkflowStage.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpWorkflowStage.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpWorkflowStage.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpWorkflowStage.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpWorkflowStage.setCreatorName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getCreatorID()));
          tmpWorkflowStage.setUpdaterName(UserInfoFactory.getUserFullName(tmpWorkflowStage.getUpdaterID()));
          return(tmpWorkflowStage);
        } else {
          return null;
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  /**
   * Deletes all the stage of the given workflow step
   *
   * @param workflowStepID The workflow step ID
   * @throws ApplicationException
   */
  public void deleteByWorkflowStepID(Integer workflowStepID) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   MTM_WF_STAGE_WF_STEP ");
        sqlStat.append("WHERE  WORKFLOW_STEP_ID= ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, workflowStepID);
        updateCnt = preStat.executeUpdate();
        if (updateCnt < 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
}
